import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import ElementUI from '../components/ElementUI.vue'
import Home from '../components/Home.vue'
import user from '../components/user/user.vue'
import ItemCat from '../components/items/ItemCat.vue'
import Item from '../components/items/Item.vue'
import AddItem from '../components/items/addItem.vue'
//使用路由机制
Vue.use(VueRouter)
const routes = [
  {path: '/', redirect: '/login'},
  {path: '/login', component: Login},
  {path: '/elementUI', component: ElementUI},
  {path: '/home',component: Home,name: Home,children: [
    {path: '/user',component: user},
    {path: '/itemCat',component: ItemCat},
    {path: '/item',component: Item},
    {path: '/item/addItem',component: AddItem }
  ]},

]

const router = new VueRouter({
     mode: 'history',
     routes
})

/* 路由导航守卫
 说明：beforeEach 用户每次请求目标网址时都会被拦截
 参数：
     to：请求网址对象
     from：请求来源
     next：请求的放行
 */
router.beforeEach((to,from,next) => {
  if(to.path === '/login'){
    //如果请求的路径时login 不进行拦截 直接放行
    return next()
  }
  //获取后台返回的token 判断是否有token
  let token = window.sessionStorage.getItem("token") //通过键值获取token的值
  if(token !== null && token !== ''){
    //有值直接放行 跳转到指定页面
    return next()
  }
  //数据为空跳转登录页面
  next('/login')
  alert("请输入用户名和密码")
})

export default router
